package io.renren.modules.app.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.annotation.LoginUser;
import io.renren.modules.app.entity.*;
import io.renren.modules.app.service.*;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 购物车api
 * @author zzh
 * @email 862583291@qq.com
 * @date 2019-6-15 12:27
 */
@Api("购物车api")
@RestController
@RequestMapping("/app/v1/cart")
public class ApiCartController {
    @Autowired
    private ApiGoodsService apiGoodsService;

    @Autowired
    private ApiProductService apiProductService;

    @Autowired
    private ApiCartService apiCartService;

    @Autowired
    private ApiSysParameterService apiSysParameterService;

    @Autowired
    private ApiAddressService apiAddressService;

    @Autowired
    private ApiCouponService apiCouponService;
    /**
     *加入购物车
     */
    @Login
    @PostMapping("/add")
    public R add(@LoginUser UserVo userVo, @RequestBody Map<String, Object> params){
        Integer goodsId = Integer.parseInt(params.get("goodsId").toString());
        Integer productId = Integer.parseInt(params.get("productId").toString());
        Integer number = Integer.parseInt(params.get("number").toString());
        String checkedSpecText = params.get("checkedSpecText").toString();
        //判断商品是否可以购买
        GoodsVo goodsInfo = apiGoodsService.getById(goodsId);
        if (null == goodsInfo || goodsInfo.getIsDelete() == 1 || goodsInfo.getIsOnSale() != 1) {
            return R.error("商品已下架");
        }
        //取得规格的信息,判断规格库存
        ProductVo productInfo = apiProductService.getById(productId);
        if (null == productInfo || productInfo.getGoodsNumber() < number) {
            return R.error("库存不足");
        }
        //判断购物车中是否存在此规格商品
        List<CartVo> cartInfoList = apiCartService.list(
                new QueryWrapper<CartVo>().eq("goods_id",goodsId).eq("product_id",productId).eq("user_id",userVo.getUserId())
        );
        CartVo cartInfo = null != cartInfoList && cartInfoList.size() > 0 ? cartInfoList.get(0) : null;
        if (null == cartInfo) {
            //添加操作
            cartInfo = new CartVo();
            cartInfo.setGoodsId(goodsId);
            cartInfo.setProductId(productId);
            cartInfo.setGoodsSn(productInfo.getGoodsSn());
            cartInfo.setGoodsName(goodsInfo.getName());
            cartInfo.setListPicUrl(goodsInfo.getListPicUrl());
            cartInfo.setNumber(number);
            cartInfo.setSessionId("1");
            cartInfo.setUserId(userVo.getUserId());
            cartInfo.setRetailPrice(productInfo.getRetailPrice());
            cartInfo.setMarketPrice(productInfo.getMarketPrice());
            cartInfo.setGoodsSpecifitionNameValue(checkedSpecText);
            cartInfo.setGoodsSpecifitionIds(productInfo.getGoodsSpecificationIds());
            cartInfo.setChecked(1);
            apiCartService.save(cartInfo);
        } else {
            //如果已经存在购物车中，则数量增加
            if (productInfo.getGoodsNumber() < (number + cartInfo.getNumber())) {
                return R.error("库存不足");
            }
            cartInfo.setNumber(cartInfo.getNumber() + number);
            apiCartService.updateById(cartInfo);
        }
        return R.ok("添加成功");
    }

    /**
     *获取购物车列表
     */
    @Login
    @GetMapping("/list")
    public R list(@LoginUser UserVo userVo){
        List<CartVo> cartList = apiCartService.list(
                new QueryWrapper<CartVo>().eq("user_id",userVo.getUserId())
        );
        //获取购物车统计信息
        Integer goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0.00);
        Integer checkedGoodsCount = 0;
        BigDecimal checkedGoodsAmount = new BigDecimal(0.00);
        for (CartVo cartItem : cartList) {
            goodsCount += cartItem.getNumber();
            goodsAmount = goodsAmount.add(cartItem.getRetailPrice().multiply(new BigDecimal(cartItem.getNumber())));
            if (null != cartItem.getChecked() && 1 == cartItem.getChecked()) {
                checkedGoodsCount += cartItem.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(cartItem.getRetailPrice().multiply(new BigDecimal(cartItem.getNumber())));
            }
        }
        return R.ok()
                .put("cartList",cartList)
                .put("goodsCount",goodsCount)
                .put("goodsAmount",goodsAmount)
                .put("checkedGoodsCount",checkedGoodsCount)
                .put("checkedGoodsAmount",checkedGoodsAmount);
    }

    /**
     *删除
     */
    @Login
    @PostMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
        apiCartService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     *是否选择商品，如果已经选择，则取消选择，批量操作
     *
     */
    @Login
    @PostMapping("/checked")
    public R checked(@LoginUser UserVo userVo, @RequestBody Map<String, Object> params){
        Integer isChecked = Integer.parseInt(params.get("isChecked").toString());
        String ids = params.get("ids").toString();
        if(StringUtil.isNullOrEmpty(isChecked)||StringUtil.isNullOrEmpty(ids)){
            return R.error("参数不能为空");
        }
        String[] idArray = ids.split(",");
        apiCartService.updateCheck(idArray,isChecked,userVo.getUserId());
        return list(userVo);
    }

    /**
     *订单提交前的检验和填写相关订单信息
     * productIds
     * addressId
     */
    @Login
    @GetMapping("/checkout")
    public R checkout(@LoginUser UserVo userVo,@RequestParam Map<String, Object> params){
        Integer addressId = Integer.parseInt(params.get("addressId").toString());
        Integer couponId = Integer.parseInt(params.get("couponId").toString());
        String type = params.get("type").toString();
        //根据收货地址计算运费
        BigDecimal freightPrice = new BigDecimal(0.00);
        SysParameterVo freightPriceParameter = apiSysParameterService.getOne(
                new QueryWrapper<SysParameterVo>().eq("parameter","freight_price")
        );
        SysParameterVo minGoodsPriceParameter = apiSysParameterService.getOne(
                new QueryWrapper<SysParameterVo>().eq("parameter","min_goods_price")
        );
        //默认收货地址
        List<AddressVo> addressList = new ArrayList<AddressVo>();
        AddressVo address = null;
        if (!StringUtil.isNullOrEmpty(addressId)) {
            address = apiAddressService.getById(addressId);
        }
        if(StringUtil.isNullOrEmpty(address)){
            addressList = apiAddressService.list(
                new QueryWrapper<AddressVo>().eq("user_id",userVo.getUserId()).orderByDesc("is_default")
            );
        }
        if (!StringUtil.isNullOrEmpty(addressList)) {
            address = addressList.get(0);
        }
        //获取要购买的商品和总价
        ArrayList<CartVo> checkedGoodsList = new ArrayList();
        BigDecimal goodsTotalPrice = new BigDecimal(0.00);
        if (type.equals("cart")) {
            R r = list(userVo);
            for (CartVo cartEntity : (List<CartVo>) r.get("cartList")) {
                if (cartEntity.getChecked() == 1) {
                    checkedGoodsList.add(cartEntity);
                }
            }
            goodsTotalPrice = (BigDecimal) r.get("checkedGoodsAmount");
        }else{// 是直接购买的

        }

        //获取可用的优惠券信息
        BigDecimal couponPrice = new BigDecimal(0.00);
        if (couponId != null && couponId != 0) {
            CouponVo couponVo = apiCouponService.getUserCoupon(couponId);
            if (!StringUtil.isNullOrEmpty(couponVo)) {
                couponPrice = couponVo.getTypeMoney();
            }
        }

        //判断是否需要加运费
        if(!StringUtil.isNullOrEmpty(freightPriceParameter) && !StringUtil.isNullOrEmpty(minGoodsPriceParameter)){
            BigDecimal minGoodsPrice = new BigDecimal(minGoodsPriceParameter.getParameterValue());
            if( minGoodsPrice.compareTo(goodsTotalPrice) > 0 ){
                freightPrice = new BigDecimal(freightPriceParameter.getParameterValue());
            }
        }
        //订单的总价
        BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);
        //实际支付订单金额
        BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);  //减去其它支付的金额后，要实际支付的金额

        return R.ok().put("address",address)
                .put("checkedGoodsList",checkedGoodsList)
                .put("freightPrice",freightPrice)
                .put("couponPrice",couponPrice)
                .put("goodsTotalPrice",goodsTotalPrice)
                .put("orderTotalPrice",orderTotalPrice)
                .put("actualPrice",actualPrice);
    }

    /**
     *修改购物车商品数量
     */
    @Login
    @PostMapping("/update")
    public R update(@LoginUser UserVo userVo, @RequestBody Map<String, Object> params){
        Integer goodsId = Integer.parseInt(params.get("goodsId").toString());
        Integer productId = Integer.parseInt(params.get("productId").toString());
        Integer number = Integer.parseInt(params.get("number").toString());
        //判断商品是否可以购买
        GoodsVo goodsInfo = apiGoodsService.getById(goodsId);
        if (null == goodsInfo || goodsInfo.getIsDelete() == 1 || goodsInfo.getIsOnSale() != 1) {
            return R.error("商品已下架");
        }
        //取得规格的信息,判断规格库存
        ProductVo productInfo = apiProductService.getById(productId);
        if (null == productInfo || productInfo.getGoodsNumber() < number) {
            return R.error("库存不足");
        }
        //判断购物车中是否存在此规格商品
        List<CartVo> cartInfoList = apiCartService.list(
                new QueryWrapper<CartVo>().eq("goods_id",goodsId).eq("product_id",productId).eq("user_id",userVo.getUserId())
        );
        CartVo cartInfo = null != cartInfoList && cartInfoList.size() > 0 ? cartInfoList.get(0) : null;
        if (!StringUtil.isNullOrEmpty(cartInfo)) {
            cartInfo.setNumber(number);
            apiCartService.updateById(cartInfo);
        }
        return list(userVo);
    }
}
